package xyz.hzxiao.base;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import xyz.hzxiao.result.JsonResult;

/**
 * @Author: scy
 * @Date: 2022-07-29 10:01
 */
@Slf4j
public abstract class AbstractGlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonResult<String> runtimeException(RuntimeException exception) {
        log.error("ERROR:", exception);
        return JsonResult.fail(exception.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonResult<String> handleBusinessException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        BindingResult result = e.getBindingResult();
        return JsonResult.fail(400, result.toString());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public JsonResult<String> paramException(IllegalArgumentException exception) {
        log.error("ERROR: {}", exception.getMessage());
        return JsonResult.fail(exception.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    public JsonResult<String> exception(Exception exception) {
        log.error("ERROR:", exception);
        return JsonResult.fail("服务器开小差了 `(*>﹏<*)′");
    }

    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    public JsonResult<String> handleBusinessException(BindException e) {
        log.error(e.getMessage(), e);
        BindingResult result = e.getBindingResult();
        return JsonResult.fail(400, result.toString());
    }

    @ExceptionHandler(MissingRequestHeaderException.class)
    public JsonResult<String> handleBusinessException(MissingRequestHeaderException e) {
        log.error(e.getMessage(), e);
        return JsonResult.fail(400, "缺少header参数:[" + e.getHeaderName() + "]");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public JsonResult<String> handleBusinessException(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return JsonResult.fail(400, "非法请求");
    }

}
